// -----------------------------------------------------------------------
//  <copyright file="DeleteDictionaryTypeCommand.cs" company="LiuliuSoft">
//      Copyright (c) 2025 66SOFT. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2025-10-17 01:10</last-date>
// -----------------------------------------------------------------------

using DaprPlus.Authorization;
using DaprPlus.Domain;
using DaprPlus.DataDicts.Domain.Entities;
using DaprPlus.DataDicts.Domain.Specs;
using DaprPlus.Domain.Entity;
using DaprPlus.MediatR;


namespace DaprPlus.DataDicts.Application.Commands;

[AuthConfig(typeof(DictionaryType), ResourceAccessType.RoleLimit, "Delete")]
public class DeleteDictionaryTypeCommand(long[] ids) : IRequest<ApiResult>, ICommand
{
    public long[] Ids { get; set; } = ids;
}

public class DeleteDictionaryTypeCommandHandler(IServiceProvider provider)
    : IRequestHandler<DeleteDictionaryTypeCommand, ApiResult>
{
    public async Task<ApiResult> Handle(DeleteDictionaryTypeCommand request, CancellationToken cancellationToken)
    {
        var logger = provider.GetLogger<DeleteDictionaryTypeCommandHandler>();
        var repository = provider.GetRequiredService<IRepository<DictionaryType>>();

        // 先查询要删除的字典类型，检查锁定状态
        var spec = new DictionaryTypeByIdsSpec(request.Ids)
            .And(new DictionaryTypeWithItemsSpec());
        var dictionaryTypes = await repository.GetAllAsync(spec, cancellationToken);

        // 检查是否有未找到的ID
        var foundIds = dictionaryTypes.Select(dt => dt.Id).ToHashSet();
        var notFoundIds = request.Ids.Except(foundIds).ToList();
        if (notFoundIds.Count > 0)
        {
            logger.LogWarning("删除字典类型时，编号为 {Ids} 的字典类型不存在", notFoundIds);
            return new ApiResult(ApiResultType.Error, $"编号为【{string.Join(", ", notFoundIds)}】的字典类型不存在");
        }

        // 检查是否有未锁定的字典类型
        var unlockedTypes = dictionaryTypes.Where(dt => !dt.IsLocked).ToList();
        if (unlockedTypes.Any())
        {
            var unlockedNames = string.Join(", ", unlockedTypes.Select(dt => dt.Name));
            logger.LogWarning("删除字典类型失败，以下字典类型未锁定，无法删除：{Names}", unlockedNames);
            return new ApiResult(ApiResultType.Locked, $"以下字典类型未锁定，无法删除：【{unlockedNames}】");
        }

        var deleteSpec = new DictionaryTypeByIdsSpec(request.Ids);
        var count = await repository.DeleteBatchAsync(deleteSpec, cancellationToken);

        logger.LogInformation("编号为{Ids}的字典类型信息删除成功，数量：{Count}", request.Ids, count);

        return ApiResult.SuccessOrNoChanged(count > 0, $"{count}个字典类型信息删除成功");
    }
}
